package com.bishe.tax.controller.sys;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("getImg")
public class ImageController {
	private String imagesPath = "D:/TAXIMG/"; // 定义上传文件的存放位置

	@GetMapping(value = "no")
	public void getImage(@RequestParam(value = "imgFile") String imgFile,
			@RequestParam(value = "type", required = false) String type, HttpServletResponse response)
			throws IOException {
		if (StringUtils.isNotBlank(type)) {
			download(imgFile, response);
		} else {
			try (FileInputStream fileIs = new FileInputStream(imagesPath + imgFile);
					OutputStream outStream = response.getOutputStream();) {

				int i = fileIs.available(); // 得到文件大小
				byte data[] = new byte[i];
				fileIs.read(data); // 读数据
				response.setContentType("image/*"); // 设置返回的文件类型
				outStream.write(data); // 输出数据
				outStream.flush();
			} catch (Exception e) {
				return;
			}
		}
	}

	public void download(String imgFile, HttpServletResponse response) throws IOException {
		File file = new File(imagesPath + imgFile);

		if (file.exists()) {
			// 设置MIME类型
			response.setContentType("application/octet-stream");
			String suffix = getFileSuffix(imgFile);
			// 设置头信息,设置文件下载时的默认文件名，同时解决中文名乱码问题
			response.addHeader("Content-disposition",
					"attachment;filename=" + UUID.randomUUID().toString() + "." + suffix);
			try (InputStream inputStream = new FileInputStream(file);
					ServletOutputStream outputStream = response.getOutputStream();) {
				byte[] bs = new byte[1024];
				while ((inputStream.read(bs) > 0)) {
					outputStream.write(bs);
				}
			} catch (Exception e) {
				return;
			}
		}
	}

	private String getFileSuffix(String fileName) {
		String Suffix = "";
		if (fileName != null) {
			String[] str = fileName.split("\\.");
			if (str.length > 0) {
				Suffix = str[str.length - 1];
			}
		}
		return Suffix;
	}

}
